package com.bjpowernode.boss.mvc.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bjpowernode.boss.common.consants.SysConstants;
import com.bjpowernode.boss.common.enums.ResponseCode;
import com.bjpowernode.boss.convert.UserConvert;
import com.bjpowernode.boss.dao.entity.UserInfo;
import com.bjpowernode.boss.mvc.models.AjaxResult;
import com.bjpowernode.boss.mvc.models.form.user.UserEditForm;
import com.bjpowernode.boss.mvc.models.pages.PageInfo;
import com.bjpowernode.boss.mvc.models.vo.user.UserInfoVo;
import com.bjpowernode.boss.mvc.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    @Resource
    private UserConvert userConvert;

    /*分页查询商户*/
    @GetMapping("/user/pageList")
    public AjaxResult pageList(Integer pageNo){
        pageNo = defPageNo(pageNo);
        IPage<UserInfo> pageResult = userService.pageList(pageNo, SysConstants.PAGE_SIZE);
        //总页数
        long totalPage = pageResult.getPages();
        //分页查询的记录
        List<UserInfo> userInfoList = pageResult.getRecords();

        //创建分页对象
        PageInfo pageInfo = new PageInfo(pageResult.getCurrent(), totalPage);

        //演示遮罩
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        //包装数据
        Map<String,Object> data = new HashMap<>();
        data.put("page",pageInfo);
        data.put("list",userConvert.toListUserInfoVo(userInfoList));

        return AjaxResult.ok(data);
    }

    /*编辑商户*/
    @PostMapping("/user/edit")
    public AjaxResult editUser(@RequestBody @Validated UserEditForm  editForm){
        userService.editUser(editForm);
        return AjaxResult.ok();
    }

    /*按主键查询*/
    @GetMapping("/user/id")
    public AjaxResult queryById(@RequestParam String userId){
        if(StrUtil.isNotBlank(userId)){
            UserInfo userInfo = userService.queryById(userId);
            UserInfoVo userInfoVo = userConvert.mapUserInfoVo(userInfo);
            return AjaxResult.ok(userInfoVo);

        }
        return AjaxResult.fail(ResponseCode.REQUEST_PARAM_ERR);
    }

    /*修改状态*/
    @PostMapping("/user/status")
    public AjaxResult editStatus(@RequestParam String userNo){
        if( StrUtil.isNotBlank(userNo)){
            userService.editStatus(userNo);
            return AjaxResult.ok();
        }
        return AjaxResult.fail(ResponseCode.REQUEST_PARAM_ERR);
    }
}
